﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Rabbit.Controls;
using Rabbit.Model;
using System.Windows.Interop;
using System.Windows.Threading;
using Rabbit.BusinessLogicLayer;
using Rabbit.Utils;

namespace MicroBlogClient
{
    /// <summary>
    /// Interaction logic for ChatWindow.xaml
    /// </summary>
    public partial class ChatWindow : Window
    {
        public string Status
        {
            get { return (string)GetValue(StatusProperty); }
            set { SetValue(StatusProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Status.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty StatusProperty =
            DependencyProperty.Register("Status", typeof(string), typeof(ChatWindow), new UIPropertyMetadata("(微兔离线)"));

        public string Message
        {
            get { return (string)GetValue(MessageProperty); }
            set { SetValue(MessageProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Message.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MessageProperty =
            DependencyProperty.Register("Message", typeof(string), typeof(ChatWindow), new UIPropertyMetadata(string.Empty));
         
        public string ErrorMessage
        {
            get { return (string)GetValue(ErrorMessageProperty); }
            set { SetValue(ErrorMessageProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ErrorMessage.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ErrorMessageProperty =
            DependencyProperty.Register("ErrorMessage", typeof(string), typeof(ChatWindow), new UIPropertyMetadata(string.Empty));

        public string Ad
        {
            get { return (string)GetValue(AdProperty); }
            set { SetValue(AdProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Ad.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AdProperty =
            DependencyProperty.Register("Ad", typeof(string), typeof(ChatWindow), new UIPropertyMetadata(string.Empty));
         
        public static User Me { get; set; }
        public User CurrentUser { get; set; }
        public Func<long, string,bool> OnSendNewLetter;
        public Action<ChatWindow> OnWindowClosing;

        private DispatcherTimer timerGetStatus;

        public ChatWindow()
        {
            InitializeComponent();
            DataContext = this;

            this.Activated += new EventHandler(ChatWindow_Activated);
            this.Loaded += new RoutedEventHandler(ChatWindow_Loaded);
        }

        void ChatWindow_Loaded(object sender, RoutedEventArgs e)
        {
            timerGetStatus = new DispatcherTimer();
            timerGetStatus.Interval = TimeSpan.FromSeconds(30);
            timerGetStatus.Tick += new EventHandler(timerGetStatus_Tick);
            timerGetStatus_Tick(timerGetStatus, null);
            timerGetStatus.Start();
        }

        void timerGetStatus_Tick(object sender, EventArgs e)
        {
            UserStatus status = UserStatus.UnKnown;
            try
            {
                status = UserBL.CheckUserStatus(CurrentUser);
            }
            catch (Exception ex)
            {
                LogHelper.LogError(ex);
            }

            switch (status)
            {
                case UserStatus.UnKnown:
                    (sender as DispatcherTimer).Stop();
                    Status = "TA最近没使用过微兔";
                    break;
                case UserStatus.Offline:
                case UserStatus.Hidden:
                    Status = "微兔离线";
                    break;
                case UserStatus.Online:
                    Status = "微兔在线";
                    break;
                default:
                    break;
            }
        }

        void ChatWindow_Activated(object sender, EventArgs e)
        {
            txtMessage.Focus();
        }
         
        private void Window_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (!(e.OriginalSource.GetType().ToString().EndsWith("TextBoxView") || e.Source is ImageEx))
            {
                base.DragMove();
            }
        }

        private void ContentControl_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (!(e.OriginalSource.GetType().ToString().EndsWith("TextBoxView") || e.Source is ImageEx))
            {
                if (this.WindowState == System.Windows.WindowState.Maximized)
                {
                    this.WindowState = System.Windows.WindowState.Normal;
                }
                else
                {
                    this.WindowState = System.Windows.WindowState.Maximized;
                }
            }
        }

        private void btnTitleBarMin_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = System.Windows.WindowState.Minimized;
        }

        private void btnTitleBarMaximze_Click(object sender, RoutedEventArgs e)
        {
            if (this.WindowState == System.Windows.WindowState.Maximized)
            {
                this.WindowState = System.Windows.WindowState.Normal;
            }
            else
            {
                this.WindowState = System.Windows.WindowState.Maximized;
            }
        }

        private void btnTitleBarClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void btnSendMessage_Click(object sender, RoutedEventArgs e)
        {
            ErrorMessage = string.Empty;
            if (string.IsNullOrEmpty(Message))
            {
                ErrorMessage = "发送内容不可为空";
                return;
            }
            if (OnSendNewLetter != null)
            {
                bool isOk = OnSendNewLetter(CurrentUser.Id, Message);
                if (isOk)
                {
                    insertMessageHelper(Me.ScreenName, Message, DateTime.Now.ToLongTimeString());
                    Message = "";
                }
                else
                {
                    ErrorMessage = "发送失败,重新发送下试试？";
                }
            }
        }

        private void txtMessage_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.Enter)
            {
                btnSendMessage_Click(sender, null);
            }
        }

        public void InsertNewMessage(string screenName, string message, string dateTime)
        {
            insertMessageHelper(screenName, message, dateTime);
            Win32.FlashWindow(new WindowInteropHelper(this).Handle, true);
        }

        private void insertMessageHelper(string screenName, string message, string dateTime)
        {
            //append colored text
            string userInfo = string.Format("{0}\t{1}", screenName, dateTime);
            TextRange range = new TextRange(rtbChatRecord.Document.ContentEnd, rtbChatRecord.Document.ContentEnd);
            range.Text = userInfo;
            range.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Gray);

            //append normal text
            range = new TextRange(rtbChatRecord.Document.ContentEnd, rtbChatRecord.Document.ContentEnd);
            range.Text +=Environment.NewLine;
            range.Text +=message;
            range.Text += Environment.NewLine + Environment.NewLine;

            range.ClearAllProperties();
            rtbChatRecord.ScrollToEnd();
        }

        private void mainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.Hide();
            e.Cancel = true;
        }
    }
}
